package com.example.myapplication.ui.loan;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.myapplication.App;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;
import com.example.myapplication.entity.BorrowAndLoan;
import com.example.myapplication.entity.Income;
import com.example.myapplication.greendao.BorrowAndLoanDao;
import com.example.myapplication.greendao.DaoSession;
import com.example.myapplication.greendao.IncomeDao;
import com.tandong.bottomview.view.BottomView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class LoanFragment extends Fragment {
    private Button loan;
    private Button borrow;
    private ListView testLv;//ListView组件
    private Button updateDataBtn;//动态加载数据组件
    private List<String> dataList = new ArrayList<>();//存储数据
    private App app;
    private DaoSession daoSession;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_loan, null);
        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        borrow = getActivity().findViewById(R.id.bt_borrow);
        loan = getActivity().findViewById(R.id.bt_loan);
        testLv = (ListView) getActivity().findViewById(R.id.test_lv);
        initList("borrow");     //默认显示借钱信息
        warning();

        //借款
        borrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initList("borrow");
                borrow.setBackgroundResource(R.drawable.button_select);
                loan.setBackgroundResource(R.drawable.button_normal);
                warning();
            }
        });


        //贷款
        loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initList("loan");
                borrow.setBackgroundResource(R.drawable.button_normal);
                loan.setBackgroundResource(R.drawable.button_select);
                warning();
            }
        });
    }
    public void warning(){
        app = (App) getActivity().getApplication();
        daoSession = app.getDaoSession();
        final BorrowAndLoanDao dao = daoSession.getBorrowAndLoanDao();
        List<BorrowAndLoan> daoList = dao.loadAll();
        double borrow_1 = 0.0;
        double loan_1 = 0.0;
        for(BorrowAndLoan borrowAndLoan :daoList){
            if (Integer.parseInt(borrowAndLoan.getEnd().split("-")[1])== Calendar.getInstance().get(Calendar.MONTH)+1){
                if (borrowAndLoan.getType().equals("loan")){
                    loan_1+=borrowAndLoan.getMoney();
                }else {
                    borrow_1+=borrowAndLoan.getMoney();
                }
            }
        }
        Toast.makeText(getContext(), "本月应还借款："+borrow_1+"  "+"本月应还贷款："+loan_1+"  ", Toast.LENGTH_SHORT).show();
    }
    public void initList(final String type){

        //读取数据
        app = (App) getActivity().getApplication();
        daoSession = app.getDaoSession();
        final BorrowAndLoanDao dao = daoSession.getBorrowAndLoanDao();
//                for (int i=0;i<10;i++){
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//                    Date date = new Date(System.currentTimeMillis());
//                    BorrowAndLoan borrowAndLoan = new BorrowAndLoan();
//                    borrowAndLoan.setMoney(i);
//                    borrowAndLoan.setEnd(date);
//                    borrowAndLoan.setType("borrow");
//                    dao.insert(borrowAndLoan);
//                 }
//
//                for (int i=0;i<10;i++){
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//                    Date date = new Date(System.currentTimeMillis());
//                    BorrowAndLoan borrowAndLoan = new BorrowAndLoan();
//                    borrowAndLoan.setMoney(i);
//                    borrowAndLoan.setEnd(date);
//                    borrowAndLoan.setType("loan");
//                    dao.insert(borrowAndLoan);
//                }

        List<BorrowAndLoan> daoList = dao.loadAll();
        if (daoList.isEmpty()){
            return;
        }

        ArrayList<HashMap<String,String>> myArrayList=new ArrayList<HashMap<String,String>>();
        for(BorrowAndLoan borrowAndLoan :daoList){
            if (borrowAndLoan.getType().equals(type)){
                HashMap<String, String> map = new HashMap<String, String>();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String end = simpleDateFormat.format(borrowAndLoan.getEnd());
                String end = borrowAndLoan.getEnd();
                map.put("id",String.valueOf(borrowAndLoan.getId()));
                map.put("time", ""+end);
                if (type.equals("borrow")){
                    map.put("money", "借款金额 "+borrowAndLoan.getMoney());
                }else {
                    map.put("money", "贷款金额 "+borrowAndLoan.getMoney());
                }
                myArrayList.add(map);
            }
        }
        //生成SimpleAdapter适配器对象
        SimpleAdapter mySimpleAdapter=new SimpleAdapter(getActivity(),
                myArrayList,//数据源
                R.layout.listview_loan,//ListView内部数据展示形式的布局文件listitem.xml
                new String[]{"time","money"},//HashMap中的两个key值 itemTitle和itemContent
                new int[]{R.id.time_loan,R.id.money_loan});/*布局文件listitem.xml中组件的id
                                                            布局文件的各组件分别映射到HashMap的各元素上，完成适配*/

        testLv.setAdapter(mySimpleAdapter);
        //添加点击事件
        testLv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
                                    long arg3) {
                //获得选中项的HashMap对象
                HashMap<String,String> map=(HashMap<String,String>)testLv.getItemAtPosition(arg2);
                final Long id = Long.valueOf(map.get("id"));
                final String time=map.get("time");
                final String money=map.get("money");
                final int index = arg2;

                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle("还款信息")
                        .setMessage("是否还清此款项?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(getActivity().getApplicationContext(),
                                        "你还清了了此欠款，欠款时间是："+time+money,
                                        Toast.LENGTH_SHORT).show();
                                dao.deleteByKey(id);
                                initList(type);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                return;
                            }
                        }).create();
                alertDialog.show();
            }

        });
    }
}